﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SmartMathLibrary
{
    /// <summary>
    /// Describes the kind of an analysis extremum.
    /// </summary>
    public enum ExtremumType
    {
        /// <summary>
        /// A relative or absolute maxima.
        /// </summary>
        Maxima = 0,
        /// <summary>
        /// A relative or absolute minima.
        /// </summary>
        Minima = 1,
        /// <summary>
        /// An undefined extremum.
        /// </summary>
        Undefined
    }

    /// <summary>
    /// This class represents a mathematic polynomial for real numbers.
    /// </summary>
    [Serializable]
    public class Polynomial : AbstractRealPolynomial, IPolynomial, IRealFunction
    {
        /// <summary>
        /// The components of the polynomial.
        /// </summary>
        private List<PolynomialComponent> components;

        /// <summary>
        /// Initializes a new instance of the <see cref="Polynomial"/> class.
        /// </summary>
        public Polynomial()
        {
            this.components = new List<PolynomialComponent>();
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Polynomial"/> class.
        /// </summary>
        /// <param name="poly">The polynomial to clone.</param>
        public Polynomial(Polynomial poly)
        {
            if (poly == (Polynomial) null)
            {
                throw new ArgumentNullException("poly");
            }

            this.components = poly.Components;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Polynomial"/> class.
        /// </summary>
        /// <param name="items">The number of items to create.</param>
        public Polynomial(int items)
        {
            this.components = new List<PolynomialComponent>();

            for (int i = 0; i < items; i++)
            {
                this.components.Add(new PolynomialComponent(0, 0));
            }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Polynomial"/> class.
        /// </summary>
        /// <param name="components">The list of components for the polynomial.</param>
        public Polynomial(List<PolynomialComponent> components)
        {
            if (components == (List<PolynomialComponent>) null)
            {
                throw new ArgumentNullException("components");
            }

            this.components = components;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Polynomial"/> class.
        /// </summary>
        /// <param name="data">The array of components.</param>
        public Polynomial(PolynomialComponent[] data)
        {
            if (data == (PolynomialComponent[]) null)
            {
                throw new ArgumentNullException("data");
            }

            this.components = new List<PolynomialComponent>();

            foreach (PolynomialComponent p in data)
            {
                this.components.Add(p);
            }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Polynomial"/> class.
        /// </summary>
        /// <param name="data">The coefficient data of the polynomial.</param>
        public Polynomial(double[] data)
        {
            if (data == (double[]) null)
            {
                throw new ArgumentNullException("data");
            }

            this.components = new List<PolynomialComponent>();

            for (int i = 0; i < data.Length; i++)
            {
                this.components.Add(new PolynomialComponent(data[i], i));
            }
        }

        /// <summary>
        /// Gets the components of the polynomial.
        /// </summary>
        /// <value>The components of the polynomial.</value>
        public List<PolynomialComponent> Components
        {
            get { return components; }
        }

        /// <summary>
        /// Gets the degree of the polynomial.
        /// </summary>
        /// <value>The degree of the polynomial.</value>
        public double Degree
        {
            get
            {
                this.Sort();
                return this.components[this.components.Count - 1].Exponent;
            }
        }

        /// <summary>
        /// Sets the component at a specified position.
        /// </summary>
        /// <param name="index">The specified position where the value should be set.</param>
        /// <param name="component">The component to set.</param>
        public void SetComponentAt(int index, PolynomialComponent component)
        {
            this.components[index] = component;
        }

        /// <summary>
        /// Gets a component at a specified position.
        /// </summary>
        /// <param name="index">The specified position from which the component should be returned.</param>
        /// <returns>The component of the polynomial at the specified position.</returns>
        public PolynomialComponent GetComponentAt(int index)
        {
            return this.components[index];
        }

        /// <summary>
        /// Gets the polynomial with the smallest rank.
        /// </summary>
        /// <param name="a">The first polynomial.</param>
        /// <param name="b">The second polynomial.</param>
        /// <returns>The polynomial with the smallest rank.</returns>
        public static Polynomial GetMinimumRank(Polynomial a, Polynomial b)
        {
            if (a == (Polynomial) null)
            {
                throw new ArgumentNullException("a");
            }

            if (b == (Polynomial) null)
            {
                throw new ArgumentNullException("b");
            }

            if (a.Degree < b.Degree)
            {
                return a;
            }

            return b;
        }

        /// <summary>
        /// Gets the polynomial with the biggest rank.
        /// </summary>
        /// <param name="a">The first polynomial.</param>
        /// <param name="b">The second polynomial.</param>
        /// <returns>The polynomial with the biggest rank.</returns>
        public static Polynomial GetMaximumRank(Polynomial a, Polynomial b)
        {
            if (a == (Polynomial) null)
            {
                throw new ArgumentNullException("a");
            }

            if (b == (Polynomial) null)
            {
                throw new ArgumentNullException("b");
            }

            if (a.Degree < b.Degree)
            {
                return b;
            }

            return a;
        }

        /// <summary>
        /// Checks if a specified rank exists.
        /// </summary>
        /// <param name="value">The rank to check.</param>
        /// <returns>True if the rank exists in the polynomial otherwise, false.</returns>
        public bool ExistRank(double value)
        {
            foreach (PolynomialComponent c in this.components)
            {
                if (c.Exponent == value)
                {
                    return true;
                }
            }

            return false;
        }

        /// <summary>
        /// Adds a new component to the polynomial at the front of it.
        /// </summary>
        /// <param name="component">The component to add.</param>
        public void AddInFrontOf(PolynomialComponent component)
        {
            this.components.Add(component);
        }

        /// <summary>
        /// Sorts this polynomial by ranks.
        /// </summary>
        public void Sort()
        {
            int min = 0;
            List<PolynomialComponent> tempuri = new List<PolynomialComponent>();

            while (this.components.Count > 0)
            {
                min = this.GetMinimumExponentIndex();
                tempuri.Add(this.components[min]);
                this.components.RemoveAt(min);
            }

            this.components = tempuri;
        }

        /// <summary>
        /// Gets the minimum index of the current polynomial.
        /// </summary>
        /// <returns>The minimum index of the current polynomial.</returns>
        private int GetMinimumExponentIndex()
        {
            int index = 0;
            double remind = Double.MaxValue;

            for (int i = 0; i < this.components.Count; i++)
            {
                if (this.components[i].Exponent < remind)
                {
                    index = i;
                    remind = this.components[i].Exponent;
                }
            }

            return index;
        }

        /// <summary>
        /// Adds the ranks of another polynomial to the current instance.
        /// </summary>
        /// <param name="poly">The polynomial from which the ranks should be added.</param>
        private void AddRanks(Polynomial poly)
        {
            for (int i = 0; i < poly.Components.Count; i++)
            {
                if (!this.ExistRank(poly.Components[i].Exponent))
                {
                    this.AddInFrontOf(new PolynomialComponent(0, poly.Components[i].Exponent));
                }
            }
        }

        /// <summary>
        /// Rounds the coefficients of the polynomial.
        /// </summary>
        /// <param name="decimals">The decimal precision.</param>
        public void RoundCoefficients(int decimals)
        {
            if (decimals < 0)
            {
                throw new ArgumentException("decimals < 0", "decimals");
            }
            if (15 < decimals)
            {
                throw new ArgumentException("15 < decimals", "decimals");
            }

            for (int i = 0; i < this.components.Count; i++)
            {
                this.components[i].Coefficient = Math.Round(this.components[i].Coefficient, decimals);
            }
        }

        /// <summary>
        /// Raises the specified power for each coefficient of the polynomial.
        /// </summary>
        /// <param name="power">The number to raises the power.</param>
        public void PowCoefficients(double power)
        {
            for (int i = 0; i < this.components.Count; i++)
            {
                this.components[i].Coefficient = Math.Pow(this.components[i].Coefficient, power);
            }
        }

        /// <summary>
        /// Calculates the square root of the coefficients of the polynomial.
        /// </summary>
        public void SqrtCoefficients()
        {
            for (int i = 0; i < this.components.Count; i++)
            {
                this.components[i].Coefficient = Math.Sqrt(this.components[i].Coefficient);
            }
        }

        /// <summary>
        ///  Calculates the root of the coefficients of the polynomial.
        /// </summary>
        /// <param name="root">The root.</param>
        public void RootCoefficients(double root)
        {
            for (int i = 0; i < this.components.Count; i++)
            {
                this.components[i].Coefficient = Math.Pow(this.components[i].Coefficient, 1 / root);
            }
        }

        /// <summary>
        /// Applies the log10 to every coefficient of the polynomial.
        /// </summary>
        public void Log10Coefficients()
        {
            for (int i = 0; i < this.components.Count; i++)
            {
                this.components[i].Coefficient = Math.Log10(this.components[i].Coefficient);
            }
        }

        /// <summary>
        /// Applies the log to every coefficient of the polynomial.
        /// </summary>
        public void LogCoefficients()
        {
            for (int i = 0; i < this.components.Count; i++)
            {
                this.components[i].Coefficient = Math.Log(this.components[i].Coefficient);
            }
        }

        /// <summary>
        /// Calculates the polynomial with a specified value for x.
        /// </summary>
        /// <param name="x">The specified value for x.</param>
        /// <returns>The result of the polynomial with the specified value for x.</returns>
        public override double SolveAt(double x)
        {
            double result = 0;

            foreach (PolynomialComponent c in this.components)
            {
                result += c.CalulateValue(x);
            }

            return result;
        }

        /// <summary>
        /// Determines whether the specified x is a root of the polynomial.
        /// </summary>
        /// <param name="x">The x.</param>
        /// <returns>
        /// 	<c>true</c> if the specified x is root of the polynomial; otherwise, <c>false</c>.
        /// </returns>
        public bool IsRoot(double x)
        {
            return this.SolveAt(x) == 0;
        }

        /// <summary>
        /// Creates the first derivative of the polynomial.
        /// </summary>
        /// <returns>Returns the derivative of the polynomial.</returns>
        public Polynomial Derivative()
        {
            PolynomialComponent[] tempuri = new PolynomialComponent[this.components.Count];

            this.components.CopyTo(tempuri);

            Polynomial result = new Polynomial(tempuri);

            for (int i = 0; i < result.Components.Count; i++)
            {
                result.Components[i] = result.Components[i].Derivative();
            }

            return result;
        }

        /// <summary>
        /// Normalizes the current polynomial.
        /// </summary>
        public void Normalize()
        {
            double divisor = this.GetCoefficientOfBiggestExponent();

            if (divisor != 0)
            {
                for (int i = 0; i < this.components.Count; i++)
                {
                    this.components[i].Coefficient /= divisor;
                }
            }
        }

        /// <summary>
        /// Use Horner's method to compute and return the polynomial evaluated at x.
        /// </summary>
        /// <param name="x">The x value.</param>
        /// <returns>The evaluated value of the polynomial.</returns>
        public double Evaluate(int x)
        {
            double tempuri = 0;

            for (int i = this.components.Count - 1; i >= 0; i--)
            {
                tempuri = this.components[i].Coefficient + (x * tempuri);
            }

            return tempuri;
        }

        /// <summary>
        /// Calculates one root of the polynomial by using the Newton-Raphson method.
        /// </summary>
        /// <param name="startvalue">The start value.</param>
        /// <param name="iterations">The number of iterations for finding a root.</param>
        /// <returns>One root of the polynomial.</returns>
        public double FindRoot(double startvalue, int iterations)
        {
            Polynomial derivation = this.Derivative();

            for (int i = 0; i < iterations; i++)
            {
                startvalue = startvalue -
                             (this.SolveAt(startvalue) / derivation.SolveAt(startvalue));
            }

            return startvalue;
        }

        /// <summary>
        /// Gets the coefficient with biggest exponent.
        /// </summary>
        /// <returns>The coefficient with biggest exponent.</returns>
        public double GetCoefficientOfBiggestExponent()
        {
            double biggest = this.Components[0].Coefficient;

            for (int i = 1; i < this.components.Count; i++)
            {
                if (biggest < this.Components[i].Coefficient)
                {
                    biggest = this.Components[i].Coefficient;
                }
            }

            return biggest;
        }

        /// <summary>
        /// Copies the current instance of the polynomial.
        /// </summary>
        /// <returns>The current instance of the polynomial.</returns>
        public Polynomial Copy()
        {
            PolynomialComponent[] tempuri = new PolynomialComponent[this.components.Count];

            this.components.CopyTo(tempuri);

            return new Polynomial(tempuri);
        }

        /// <summary>
        /// Implements the operator ==.
        /// </summary>
        /// <param name="a">The first polynomial.</param>
        /// <param name="b">The second polynomial.</param>
        /// <returns>The result of the operator.</returns>
        public static bool operator ==(Polynomial a, Polynomial b)
        {
            if (System.Object.ReferenceEquals(a, b))
            {
                return true;
            }

            if (((object) a == null) || ((object) b == null))
            {
                return false;
            }

            if (a.Degree != b.Degree)
            {
                return false;
            }

            for (int i = 0; i < a.Components.Count; i++)
            {
                if (a.Components[i] != b.Components[i])
                {
                    return false;
                }
            }

            return true;
        }

        /// <summary>
        /// Implements the operator !=.
        /// </summary>
        /// <param name="a">The first polynomial.</param>
        /// <param name="b">The second polynomial.</param>
        /// <returns>The result of the operator.</returns>
        public static bool operator !=(Polynomial a, Polynomial b)
        {
            return !(a == b);
        }

        /// <summary>
        /// Implements the operator +.
        /// </summary>
        /// <param name="a">The first polynomial.</param>
        /// <param name="b">The second polynomial.</param>
        /// <returns>The result of the operator.</returns>
        public static Polynomial operator +(Polynomial a, Polynomial b)
        {
            if (a == (Polynomial) null)
            {
                throw new ArgumentNullException("a");
            }

            if (b == (Polynomial) null)
            {
                throw new ArgumentNullException("b");
            }

            a.AddRanks(b);
            b.AddRanks(a);
            a.Sort();
            b.Sort();

            for (int i = 0; i < a.Components.Count; i++)
            {
                a.Components[i] += b.Components[i];
            }

            return a;
        }

        /// <summary>
        /// Implements the operator -.
        /// </summary>
        /// <param name="a">The first polynomial.</param>
        /// <param name="b">The second polynomial.</param>
        /// <returns>The result of the operator.</returns>
        public static Polynomial operator -(Polynomial a, Polynomial b)
        {
            if (a == (Polynomial) null)
            {
                throw new ArgumentNullException("a");
            }

            if (b == (Polynomial) null)
            {
                throw new ArgumentNullException("b");
            }

            a.AddRanks(b);
            b.AddRanks(a);
            a.Sort();
            b.Sort();

            for (int i = 0; i < a.Components.Count; i++)
            {
                a.Components[i] -= b.Components[i];
            }

            return a;
        }

        /// <summary>
        /// Implements the operator *.
        /// </summary>
        /// <param name="a">The first polynomial.</param>
        /// <param name="b">The second polynomial.</param>
        /// <returns>The result of the operator.</returns>
        public static Polynomial operator *(Polynomial a, Polynomial b)
        {
            if (a == (Polynomial) null)
            {
                throw new ArgumentNullException("a");
            }

            if (b == (Polynomial) null)
            {
                throw new ArgumentNullException("b");
            }

            Polynomial result = new Polynomial(a.Components.Count + b.Components.Count + 1);

            a.AddRanks(b);
            b.AddRanks(a);
            a.Sort();
            b.Sort();

            for (int i = 0; i < a.Components.Count; i++)
            {
                for (int j = 0; j < b.Components.Count; j++)
                {
                    result.Components[i + j].Exponent = a.Components[i].Exponent + b.Components[j].Exponent;
                }
            }

            for (int i = 0; i < a.Components.Count; i++)
            {
                for (int j = 0; j < b.Components.Count; j++)
                {
                    result.Components[i + j].AddCoefficient(a.Components[i] * b.Components[j]);
                }
            }

            return result;
        }

        /// <summary>
        /// Compares the current instance of a polynomial to another one.
        /// </summary>
        /// <param name="compare">The polynomial to compare.</param>
        /// <returns>True if the polynomials are even otherwise, false.</returns>
        public bool CompareTo(Polynomial compare)
        {
            if (compare == (Polynomial) null)
            {
                throw new ArgumentNullException("compare");
            }

            if (this.components.Count != compare.Components.Count)
            {
                return false;
            }

            for (int i = 0; i < this.components.Count; i++)
            {
                if (this.components[i] != compare.Components[i])
                {
                    return false;
                }
            }

            return true;
        }

        /// <summary>
        /// Removes all zero coefficients in the current polynomial.
        /// </summary>
        public void RemoveZeroCoefficients()
        {
            int i = 0;

            while (i < this.components.Count)
            {
                if (this.components[i].Coefficient == 0)
                {
                    this.components.RemoveAt(i);
                }
                else
                {
                    i++;
                }
            }
        }

        /// <summary>
        /// Multiplies the polynomial with a scalar.
        /// </summary>
        /// <param name="scalar">The scalar value.</param>
        public void MultiplyWithScalar(int scalar)
        {
            this.MultiplyWithScalar((double) scalar);
        }

        /// <summary>
        /// Multiplies the polynomial with a scalar.
        /// </summary>
        /// <param name="scalar">The scalar value.</param>
        public void MultiplyWithScalar(double scalar)
        {
            for (int i = 0; i < this.components.Count; i++)
            {
                this.components[i].Coefficient *= scalar;
            }
        }

        /// <summary>
        /// Divides the polynomial through a scalar.
        /// </summary>
        /// <param name="scalar">The scalar value.</param>
        public void DivideWithScalar(int scalar)
        {
            this.DivideWithScalar((double) scalar);
        }

        /// <summary>
        /// Divides the polynomial through a scalar.
        /// </summary>
        /// <param name="scalar">The scalar value.</param>
        public void DivideWithScalar(double scalar)
        {
            for (int i = 0; i < this.components.Count; i++)
            {
                this.components[i].Coefficient /= scalar;
            }
        }

        /// <summary>
        /// Determines whether the polynomial [has only even exponents].
        /// </summary>
        /// <returns>
        /// 	<c>true</c> if the polynomial [has only even exponents]; otherwise, <c>false</c>.
        /// </returns>
        public bool HasOnlyEvenExponents()
        {
            foreach (PolynomialComponent c in this.components)
            {
                if (c.Exponent % 2 != 0)
                {
                    return false;
                }
            }

            return true;
        }

        /// <summary>
        /// Determines whether the polynomial [has only odd exponents].
        /// </summary>
        /// <returns>
        /// 	<c>true</c> if the polynomial [has only odd exponents]; otherwise, <c>false</c>.
        /// </returns>
        public bool HasOnlyOddExponents()
        {
            return !(this.HasOnlyEvenExponents());
        }

        /// <summary>
        /// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>.
        /// </summary>
        /// <param name="obj">The <see cref="T:System.Object"/> to compare with the current <see cref="T:System.Object"/>.</param>
        /// <returns>
        /// true if the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>; otherwise, false.
        /// </returns>
        /// <exception cref="T:System.NullReferenceException">The <paramref name="obj"/> parameter is null.</exception>
        public override bool Equals(object obj)
        {
            return base.Equals(obj);
        }

        /// <summary>
        /// Serves as a hash function for a particular type.
        /// </summary>
        /// <returns>
        /// A hash code for the current <see cref="T:System.Object"/>.
        /// </returns>
        public override int GetHashCode()
        {
            return base.GetHashCode();
        }

        /// <summary>
        /// Converts the polynomial to a complex polynomial.
        /// </summary>
        /// <returns>The converted complex polynomial.</returns>
        public ComplexPolynomial ToComplexPolynomial()
        {
            List<ComplexPolynomialComponent> data = new List<ComplexPolynomialComponent>();

            for (int i = 0; i < this.components.Count; i++)
            {
                data.Add(new ComplexPolynomialComponent(new ComplexNumber
                                                            (this.components[i].Coefficient),
                                                        this.components[i].Exponent));
            }

            return new ComplexPolynomial(data);
        }

        /// <summary>
        /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
        /// </summary>
        /// <returns>
        /// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
        /// </returns>
        public override string ToString()
        {
            String result = "";

            this.Sort();

            for (int i = this.Components.Count - 1; i >= 0; i--)
            {
                result += this.Components[i].ToString() + " + ";
            }

            if (result.Length > 3)
            {
                result = result.Substring(0, result.Length - 3);
            }

            return result;
        }
    }
}